<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次编号" prop="batchCode">
        <el-input
          v-model="queryParams.batchCode"
          placeholder="请输入批次编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="缺陷名称" prop="defectName">
        <el-input
          v-model="queryParams.defectName"
          placeholder="请输入缺陷名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理状态" prop="processStatus">
        <el-select v-model="queryParams.processStatus" placeholder="请选择处理状态" clearable>
          <el-option label="未处理" value="未处理" />
          <el-option label="处理中" value="处理中" />
          <el-option label="已处理" value="已处理" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qep:nonconforming:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qep:nonconforming:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qep:nonconforming:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Download"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="nonconformingList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="50"/>
      <el-table-column label="任务编号" align="center" prop="taskCode" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="批次编号" align="center" prop="batchCode" />
      <el-table-column label="不合格数量" align="center" prop="quantity" />
      <el-table-column label="缺陷名称" align="center" prop="defectName" />
      <el-table-column label="缺陷描述" align="center" prop="defectDescription" :show-overflow-tooltip="true" />
      <el-table-column label="处理方式" align="center" prop="disposition" />
      <el-table-column label="处理状态" align="center" prop="processStatus">
        <template #default="scope">
          <el-tag :type="getProcessStatusType(scope.row.processStatus)">{{ scope.row.processStatus }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            :icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['qep:nonconforming:query']"
          >查看</el-button>
          <el-button
            link
            type="success"
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qep:nonconforming:edit']"
          >修改</el-button>
          <el-button
            link
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qep:nonconforming:remove']"
          >删除</el-button>
          <el-button
            link
            type="warning"
            :icon="Tickets"
            @click="handleRepairTask(scope.row)"
            v-if="scope.row.disposition === '返工'"
          >维修任务</el-button>
          <el-button
            link
            type="info"
            :icon="ArrowDown"
            @click="handleRegrade(scope.row)"
            v-if="scope.row.disposition === '返修后重新评级' && scope.row.processStatus === '已处理'"
          >重新评级</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改不合格品记录对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="检验任务" prop="taskId">
              <el-select v-model="form.taskId" placeholder="请选择检验任务" style="width: 100%" :disabled="readOnly">
                <el-option
                  v-for="item in taskOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select v-model="form.productId" placeholder="请选择产品" @change="handleProductChange" style="width: 100%" :disabled="readOnly">
                <el-option
                  v-for="item in productOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="批次" prop="batchId">
              <el-select v-model="form.batchId" placeholder="请选择批次" style="width: 100%" :disabled="readOnly">
                <el-option
                  v-for="item in batchOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不合格数量" prop="quantity">
              <el-input-number v-model="form.quantity" :min="1" :max="1000" label="不合格数量" :disabled="readOnly"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="缺陷" prop="defectId">
              <el-select v-model="form.defectId" placeholder="请选择缺陷" style="width: 100%" :disabled="readOnly">
                <el-option
                  v-for="item in defectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="缺陷描述" prop="defectDescription">
              <el-input v-model="form.defectDescription" type="textarea" placeholder="请输入内容" :disabled="readOnly" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理方式" prop="disposition">
              <el-select v-model="form.disposition" placeholder="请选择处理方式" :disabled="readOnly" @change="handleDispositionChange">
                <el-option label="返工" value="返工" />
                <el-option label="报废" value="报废" />
                <el-option label="返修后重新评级" value="返修后重新评级" />
                <el-option label="让步接收" value="让步接收" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理状态" prop="processStatus">
              <el-input v-model="form.processStatus" :disabled="true" placeholder="根据处理时间自动生成" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="处理人" prop="handler">
              <el-input v-model="form.handler" placeholder="请输入处理人" :disabled="readOnly" @input="handlerChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理时间" prop="handleTime">
              <el-date-picker clearable
                v-model="form.handleTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择处理时间"
                :disabled="readOnly"
                @change="handleTimeChange">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :disabled="readOnly" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!readOnly">确 定</el-button>
          <el-button @click="cancel">{{ readOnly ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listNonconforming, getNonconforming, addNonconforming, updateNonconforming, delNonconforming } from "@/api/qep/nonconforming";
import { listProduct, updateProduct } from "@/api/qep/product";
import { listBatch } from "@/api/qep/production/batch";
import { listDefect } from "@/api/qep/inspection/defect";
import { listInspectionTask } from "@/api/qep/inspection/task";
import { listRepairTask } from "@/api/qep/repair-task";
import { Search, Refresh, Plus, Edit, Delete, Download, View, Tickets, ArrowDown } from '@element-plus/icons-vue';
import { ElMessageBox, ElMessage } from 'element-plus';

export default {
  name: "Nonconforming",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 不合格品记录表格数据
      nonconformingList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        batchCode: null,
        defectName: null,
        processStatus: null
      },
      // 图标
      Search,
      Refresh,
      Plus,
      Edit,
      Delete,
      Download,
      View,
      Tickets,
      ArrowDown,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskId: [
          { required: true, message: "检验任务ID不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "产品ID不能为空", trigger: "blur" }
        ],
        batchId: [
          { required: true, message: "批次ID不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "不合格数量不能为空", trigger: "blur" }
        ],
        defectId: [
          { required: true, message: "缺陷ID不能为空", trigger: "blur" }
        ],
        defectDescription: [
          { required: true, message: "缺陷描述不能为空", trigger: "blur" }
        ],
        disposition: [
          { required: true, message: "处理方式不能为空", trigger: "change" }
        ],
        processStatus: [
          { required: true, message: "处理状态不能为空", trigger: "change" }
        ]
      },
      // 产品选项列表
      productOptions: [],
      // 批次选项列表
      batchOptions: [],
      // 缺陷选项列表
      defectOptions: [],
      // 任务选项列表
      taskOptions: [],
      // 只读状态标志
      readOnly: false,
    };
  },
  created() {
    this.getList();
    this.getProductOptions();
    this.getDefectOptions();
    this.getTaskOptions();
  },
  methods: {
    /** 查询不合格品记录列表 */
    getList() {
      this.loading = true;
      listNonconforming(this.queryParams).then(response => {
        this.nonconformingList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取产品选项列表 */
    getProductOptions() {
      listProduct({}).then(response => {
        this.productOptions = response.rows.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
      });
    },
    /** 获取批次选项列表 */
    getBatchOptions(productId) {
      const queryParams = productId ? { productId: productId } : {};
      listBatch(queryParams).then(response => {
        this.batchOptions = response.rows.map(item => {
          return {
            value: item.id,
            label: item.batchNo || item.batch_no
          };
        });
      });
    },
    /** 获取缺陷选项列表 */
    getDefectOptions() {
      listDefect({}).then(response => {
        this.defectOptions = response.rows.map(item => {
          return {
            value: item.id,
            label: item.name
          };
        });
      });
    },
    /** 获取检验任务选项列表 */
    getTaskOptions() {
      listInspectionTask({}).then(response => {
        this.taskOptions = response.rows.map(item => {
          return {
            value: item.id,
            label: item.taskCode
          };
        });
      });
    },
    /** 产品变更时加载对应批次 */
    handleProductChange(value) {
      this.form.productId = value;
      this.form.batchId = null;
      this.getBatchOptions(value);
    },
    /** 处理时间变更时更新处理状态 */
    handleTimeChange(time) {
      if (time) {
        // 有处理时间，设置为已处理
        this.form.processStatus = '已处理';
      } else if (this.form.handler) {
        // 没有处理时间但有处理人，设置为处理中
        this.form.processStatus = '处理中';
      } else {
        // 既没有处理时间也没有处理人，设置为未处理
        this.form.processStatus = '未处理';
      }
    },
    /** 处理人变更时更新处理状态 */
    handlerChange(value) {
      if (this.form.handleTime) {
        // 有处理时间，状态始终为已处理
        this.form.processStatus = '已处理';
      } else if (value) {
        // 有处理人但没有处理时间，设置为处理中
        this.form.processStatus = '处理中';
      } else {
        // 没有处理人也没有处理时间，设置为未处理
        this.form.processStatus = '未处理';
      }
    },
    /** 处理方式改变时的操作 */
    handleDispositionChange(value) {
      // 如果选择了"返修后重新评级"，提示用户应该先执行返工流程
      if (value === '返修后重新评级') {
        ElMessage({
          type: 'info',
          message: '选择此处理方式后，需要先创建维修任务并完成维修，然后进行重新评级'
        });
        // 自动设置处理状态为"处理中"
        this.form.processStatus = '处理中';
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskId: null,
        productId: null,
        batchId: null,
        quantity: 1,
        defectId: null,
        defectDescription: null,
        disposition: null,
        handler: null,
        handleTime: null,
        processStatus: '未处理',
        remark: null
      };
      this.resetForm("form");
      this.batchOptions = []; // 清空批次选项
      this.readOnly = false; // 重置只读状态
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // 重置只读状态
      this.readOnly = false;
      this.open = true;
      this.title = "添加不合格品记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // 重置只读状态
      this.readOnly = false;
      const id = row.id || this.ids[0];
      getNonconforming(id).then(response => {
        this.form = response.data;
        // 如果有产品ID，加载对应的批次列表
        if (this.form.productId) {
          this.getBatchOptions(this.form.productId);
        }
        
        // 确保处理状态是根据处理人和处理时间自动生成的
        this.updateProcessStatus();
        
        this.open = true;
        this.title = "修改不合格品记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 在提交前更新处理状态
          this.updateProcessStatus();
          
          // 对于降级处理方式，避免直接标记为已处理
          if (this.form.disposition === '返修后重新评级' && this.form.processStatus === '已处理') {
            ElMessageBox.confirm('返修后重新评级需要通过重新评级按钮完成，是否继续保存?', '警告', {
              confirmButtonText: '继续保存',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.saveForm();
            }).catch(() => {
              // 用户取消保存
            });
          } else {
            this.saveForm();
          }
        }
      });
    },
    /** 更新处理状态 */
    updateProcessStatus() {
      if (this.form.handleTime) {
        this.form.processStatus = '已处理';
      } else if (this.form.handler) {
        this.form.processStatus = '处理中';
      } else {
        this.form.processStatus = '未处理';
      }
    },
    /** 保存表单数据 */
    saveForm() {
      if (this.form.id != null) {
        updateNonconforming(this.form).then(response => {
          ElMessage.success("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addNonconforming(this.form).then(response => {
          ElMessage.success("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      ElMessageBox.confirm('是否确认删除不合格品记录编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return delNonconforming(ids);
      }).then(() => {
        this.getList();
        ElMessage.success("删除成功");
      }).catch(() => {
        // 取消操作时不需要处理
      });
    },
    /** 查看详情按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      getNonconforming(id).then(response => {
        this.form = response.data;
        // 如果有产品ID，加载对应的批次列表
        if (this.form.productId) {
          this.getBatchOptions(this.form.productId);
        }

        // 确保处理状态是根据处理人和处理时间自动生成的
        this.updateProcessStatus();

        // 创建一个只读状态标志
        this.readOnly = true;
        this.open = true;
        this.title = "查看不合格品记录";
      });
    },
    /** 跳转到维修任务页面 */
    handleRepairTask(row) {
      const nonconformingId = row.id;
      
      // 检查处理方式，只有返工的不合格品才能创建维修任务
      if (row.disposition !== '返工') {
        ElMessage({
          type: 'warning',
          message: '只有返工处理方式的不合格品才能创建维修任务'
        });
        return;
      }
      
      // 先检查是否已存在维修任务
      ElMessageBox.confirm('是否为该不合格品创建维修任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确保路由路径与router/index.js中定义的一致
        this.$router.push({ 
          path: '/nonconforming/repair-task',
          query: { nonconformingId: nonconformingId }
        });
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    /** 处理产品重新评级 */
    handleRegrade(row) {
      const nonconformingId = row.id;
      
      // 检查处理方式，只有"返修后重新评级"的不合格品才能执行评级操作
      if (row.disposition !== '返修后重新评级') {
        ElMessage({
          type: 'warning',
          message: '只有选择"返修后重新评级"处理方式的不合格品才能执行此操作'
        });
        return;
      }
      
      // 检查是否已维修完成
      // 查询与此不合格品关联的维修任务
      listRepairTask({ nonconformingId: row.id }).then(response => {
        const repairTasks = response.rows;
        let hasCompletedTask = false;
        
        if (repairTasks && repairTasks.length > 0) {
          // 检查是否有已完成的维修任务
          hasCompletedTask = repairTasks.some(task => 
            task.status === '已完成' || task.statusText === '已完成'
          );
          
          if (!hasCompletedTask) {
            ElMessage({
              type: 'warning',
              message: '请先完成维修任务后再进行重新评级'
            });
            return;
          }
          
          // 继续处理重新评级
          this.processRegrade(row);
        } else {
          ElMessage({
            type: 'warning',
            message: '未找到关联的维修任务，请先创建并完成维修任务'
          });
        }
      }).catch(() => {
        ElMessage.error('获取维修任务信息失败');
      });
    },
    
    /** 处理重新评级逻辑 */
    processRegrade(row) {
      // 获取产品信息
      listProduct({ productId: row.productId }).then(response => {
        if (response.rows && response.rows.length > 0) {
          const product = response.rows[0];
          
          // 获取当前等级
          const currentGrade = product.grade || '优等品';
          
          // 等级选项
          const gradeOptions = ['优等品', '一等品', '二等品', '三等品', '合格品', '次品'];
          
          ElMessageBox.prompt(
            `产品当前等级: ${currentGrade}\n请选择重新评级后的等级:`, 
            '产品重新评级', 
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputPlaceholder: '请选择评级',
              inputValue: currentGrade,
              inputType: 'select',
              inputOptions: gradeOptions.map(opt => ({ label: opt, value: opt })),
              type: 'info'
            }
          ).then(({ value }) => {
            if (!value) {
              ElMessage({
                type: 'warning',
                message: '请选择产品等级'
              });
              return;
            }
            
            // 更新产品信息
            const updatedProduct = { ...product };
            const oldGrade = updatedProduct.grade || '优等品';
            updatedProduct.grade = value;
            
            updateProduct(updatedProduct).then(() => {
              // 更新不合格品记录
              const nonconforming = { ...row };
              
              // 设置处理状态为已处理
              nonconforming.processStatus = '已处理';
              
              // 更新处理人和处理时间
              if (!nonconforming.handler) {
                try {
                  nonconforming.handler = localStorage.getItem('userName') || '系统用户';
                } catch (e) {
                  nonconforming.handler = '系统用户';
                }
              }
              
              if (!nonconforming.handleTime) {
                nonconforming.handleTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
              }
              
              // 更新备注，添加重新评级信息
              nonconforming.remark = (nonconforming.remark || '') + 
                `\n[${new Date().toLocaleString()}] 维修后产品已从 ${oldGrade} 重新评级为 ${value}`;
              
              // 更新不合格品记录
              updateNonconforming(nonconforming).then(() => {
                ElMessage.success(`产品 ${product.name} 已成功从 ${oldGrade} 重新评级为 ${value}，不合格品处理已完成`);
                this.getList(); // 刷新列表
              }).catch(error => {
                console.error('更新不合格品记录失败:', error);
                ElMessage.error('更新不合格品状态失败，请手动更新状态');
              });
            }).catch(() => {
              ElMessage.error('产品重新评级失败，请稍后重试');
            });
          }).catch(() => {
            ElMessage({
              type: 'info',
              message: '已取消重新评级操作'
            });
          });
        } else {
          ElMessage.error('未找到相关产品信息');
        }
      }).catch(() => {
        ElMessage.error('获取产品信息失败');
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      ElMessageBox.confirm('是否确认导出所有不合格品记录数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.download('qep/nonconforming/export', {
          ...queryParams
        }, `不合格品记录_${new Date().getTime()}.xlsx`);
      }).catch(() => {
        // 取消操作时不需要处理
      });
    },
    /** 获取处理状态样式类型 */
    getProcessStatusType(status) {
      if (status === '已处理') {
        return 'success';
      } else if (status === '处理中') {
        return 'warning';
      } else if (status === '已完成') {
        return 'success';
      } else {
        return 'info';
      }
    },
  }
};
</script>

<style scoped>
.el-tag {
  margin-right: 5px;
}
</style> 